ngx.header["Access-Control-Allow-Origin"] = "*"
ngx.header["Access-Control-Allow-Headers"] = "Content-Type"
ngx.header["Access-Control-Allow-Methods"] = "POST,GET,OPTIONS,DELETE"

--[[
local redis_client = require "lib.redis"
local redis = redis_client:new()
]]

function string.split(str, delimiter)
    if str == nil or str == '' or delimiter == nil then
        return nil
    end

    local result = {}

    for match in (str..delimiter):gmatch("(.-)"..delimiter) do
        table.insert(result, match)
    end

    return result
end

function ngx.err (message)
    ngx.say('{"code":10000,"message":"', message,'"}')
end

function ngx.record_user()
    local args = ngx.req.get_uri_args()
    local redis_client = require "lib.redis"
    local redis = redis_client:new()
    local uid = args.uid
    local username = args.userName or args.nickname
    local tenant_id = args.TenantID or ""

    if nil == username or "" == username then
        username = args.username
    end

    if nil == uid or "" == uid then
        return
    end

    if nil == username or "" == username then
        return
    end

    local uniqueid = string.lower(tenant_id..uid);

    local has, _ = redis:hget("users:recorded", uniqueid)

    if has then
        return
    end

    -- 奇葩的命名方式
    local profile = [[{
        "uid":"%s",
        "source":"%s",
        "tenant_id":"%s",
        "username":"%s",
        "nickname":"%s",
        "avatar":"%s",
        "mobile":"%s",
        "uniqueid":"%s"
    }]]

    redis:lpush("_profiles", string.format(
        profile,
        uid,
        args.SourceID or "",
        args.TenantID or "",
        username,
        args.nickname or "",
        args.avatar or "",
        args.mobile or "",
        uniqueid
    ))
    redis:hset("users:recorded", uniqueid, 1)
end
--获取客户端ip
function get_client_ip()
    local headers=ngx.req.get_headers()
    local ip=headers["X-REAL-IP"] or headers["X_FORWARDED_FOR"] or ngx.var.remote_addr or "0.0.0.0"
    return ip
end